<template>
  <div>
    <!-- 面包屑 -->
    <el-breadcrumb separator-class="el-icon-arrow-right">
      <el-breadcrumb-item :to="{ path: '/home' }">首页</el-breadcrumb-item>
      <el-breadcrumb-item>权限管理</el-breadcrumb-item>
      <el-breadcrumb-item>角色列表</el-breadcrumb-item>
    </el-breadcrumb>
    <!-- 列表 -->
    <el-card>
      <el-row>
        <el-col>
          <el-button type="primary" @click="addDialogVisible = true">添加角色</el-button>
        </el-col>
        <el-col>
          <el-table :data="rolesList" border stripe>
            <!-- 折叠列表 -->
            <el-table-column type="expand">
              <template slot-scope="scope">
                <el-row
                  v-for="(item1,i1) in scope.row.children"
                  :key="item1.id"
                  :class="['borbot',i1===0 ? 'bortop':'','cvcenter']"
                >
                  <!-- 权限一级渲染 -->
                  <el-col :span="5">
                    <el-tag closable @close="removeId(scope.row,item1.id)">{{item1.authName}}</el-tag>
                    <i class="el-icon-caret-right"></i>
                  </el-col>
                  <!-- 权限二级和三级渲染 -->
                  <el-col :span="19">
                    <el-row
                      v-for="(item2,i2) in item1.children"
                      :key="item2.id"
                      :class="[i2===0?'':'bortop','cvcenter']"
                    >
                      <!-- 二级 -->
                      <el-col :span="6">
                        <el-tag
                          type="success"
                          closable
                          @close="removeId(scope.row,item2.id)"
                        >{{item2.authName}}</el-tag>
                        <i class="el-icon-caret-right"></i>
                      </el-col>
                      <!-- 三级 -->
                      <el-col :span="18">
                        <el-tag
                          type="warning"
                          v-for="(item3) in item2.children"
                          :key="item3.id"
                          closable
                          @close="removeId(scope.row,item3.id)"
                        >{{item3.authName}}</el-tag>
                      </el-col>
                    </el-row>
                  </el-col>
                </el-row>
              </template>
            </el-table-column>
            <el-table-column type="index" label="#"></el-table-column>
            <el-table-column label="角色名称" prop="roleName"></el-table-column>
            <el-table-column label="角色描述" prop="roleDesc"></el-table-column>
            <el-table-column label="操作">
              <template slot-scope="scope">
                <el-button
                  size="small"
                  type="primary"
                  icon="el-icon-edit"
                  @click="editRoles(scope.row.id)"
                >编辑</el-button>
                <el-button
                  size="small"
                  type="danger"
                  icon="el-icon-delete"
                  @click="delRole(scope.row.id)"
                >删除</el-button>
                <el-button
                  size="small"
                  type="warning"
                  icon="el-icon-setting"
                  @click="setRolesButton(scope.row)"
                >分配权限</el-button>
              </template>
            </el-table-column>
          </el-table>
        </el-col>
      </el-row>
    </el-card>
    <!-- 编辑角色 -->
    <el-dialog title="编辑角色" :visible.sync="editDialogVisible" width="50%" @close="emptyEditForm">
      <el-form :model="editForm" ref="editFormRef" :rules="editFormRules" label-width="80px">
        <el-form-item label="角色名称" prop="roleName">
          <el-input v-model="editForm.roleName"></el-input>
        </el-form-item>
        <el-form-item label="角色描述">
          <el-input v-model="editForm.roleDesc"></el-input>
        </el-form-item>
      </el-form>

      <span slot="footer" class="dialog-footer">
        <el-button @click="editDialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="subEdit">确 定</el-button>
      </span>
    </el-dialog>

    <!-- 添加角色 -->

    <el-dialog title="添加角色" :visible.sync="addDialogVisible" width="50%" @close="emptyAddForm">
      <el-form :model="addForm" ref="addFormRef" :rules="addRolesRules" label-width="80px">
        <el-form-item label="角色名称" prop="roleName">
          <el-input v-model="addForm.roleName"></el-input>
        </el-form-item>
        <el-form-item label="角色描述" prop="roleDesc">
          <el-input v-model="addForm.roleDesc"></el-input>
        </el-form-item>
      </el-form>

      <span slot="footer" class="dialog-footer">
        <el-button @click="addDialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="addRole">确 定</el-button>
      </span>
    </el-dialog>

    <!-- 分配角色权限 -->
    <el-dialog
      title="分配角色权限"
      :visible.sync="setRolesDialogVisible"
      width="30%"
      @close="setRightsDialogClose"
    >
      <el-tree
        :data="setRolesList"
        :props="defaultProps"
        show-checkbox
        node-key="id"
        default-expand-all
        :default-checked-keys="defaultKeys"
        ref="treeRef"
      ></el-tree>

      <span slot="footer" class="dialog-footer">
        <el-button @click="setRolesDialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="addRolesRights">确 定</el-button>
      </span>
    </el-dialog>
  </div>
</template>
<script>
export default {
  data() {
    return {
      rolesList: [],
      editDialogVisible: false,
      editForm: {
        roleName: "",
        roleDesc: "",
      },
      editFormRules: {
        roleName: [
          { required: true, message: "请输入角色名", trigger: "blur" },
          { min: 2, max: 5, message: "长度在 2 到 5 个字符", trigger: "blur" },
        ],
      },
      //新增角色
      addDialogVisible: false,
      addForm: {
        roleName: "",
        roleDesc: "",
      },
      addRolesRules: {
        roleName: [
          { required: true, message: "请输入角色名", trigger: "blur" },
          { min: 2, max: 5, message: "长度在 2 到 5 个字符", trigger: "blur" },
        ],
      },
      // 分配角色权限
      setRolesDialogVisible: false,
      setRolesList: [],
      defaultProps: {
        label: "authName",
        children: "children",
      },
      // 角色id
      roleId: "",
      // 默认权限
      defaultKeys: [],
    };
  },
  created() {
    this.getRolesList();
    console.log(this.defaultKeys);
  },
  methods: {
    // 获取列表数据
    getRolesList() {
      this.$http({
        url: "roles",
      }).then((res) => {
        if (res.data.meta.status != 200) {
          return;
        }
        this.rolesList = res.data.data;
      });
    },
    // 编辑角色
    editRoles(id) {
      //显示编辑框
      this.editDialogVisible = true;
      // 查询角色详情
      this.$http.get("roles/" + id).then((res) => {
        console.log(res);
        this.editForm = res.data.data;
      });
    },
    // 提交编辑
    subEdit() {
      this.$refs.editFormRef.validate((valid) => {
        if (valid) {
          this.$http
            .put("roles/" + this.editForm.roleId, this.editForm)
            .then(() => {
              // console.log(res);
              this.$message.success("修改成功");
              this.editDialogVisible = false;
              this.getRolesList();
            });
        }
      });
    },
    //清除编辑角色表单项的校验结果
    emptyEditForm() {
      this.$refs.editFormRef.clearValidate();
    },
    // 删除角色
    delRole(id) {
      this.$confirm("此操作将永久删除该角色, 是否继续?", "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning",
      })
        .then(() => {
          this.$http.delete("roles/" + id).then((res) => {
            if (res.data.meta.status == 200) {
              this.$message.success("删除成功");
              this.getRolesList();
            } else {
              this.$message.error("删除失败");
            }
          });
        })
        .catch(() => {
          this.$message({
            type: "info",
            message: "已取消删除",
          });
        });
    },
    //新增角色
    addRole() {
      this.$refs.addFormRef.validate((valid) => {
        if (valid) {
          this.$http({
            url: "roles",
            method: "post",
            data: this.addForm,
          }).then((res) => {
            console.log(res);
            if (res.data.meta.status == 201) {
              this.$message.success("新增角色成功");
              this.addDialogVisible = false;
              this.getRolesList();
            } else {
              this.$message.error("新增角色失败");
            }
          });
        }
      });
    },
    //清空添加角色表单
    emptyAddForm() {
      this.$refs.addFormRef.resetFields();
    },
    //删除角色三级权限
    removeId(role, rightId) {
      this.$confirm("此操作将永久删除该角色权限, 是否继续?", "温馨提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning",
      })
        .then(() => {
          this.$http
            .delete(`roles/${role.id}/rights/${rightId}`)
            .then((res) => {
              if (res.data.meta.status == 200) {
                this.$message.success("删除成功!");
                // 重新赋值，防止页面的刷新，给用户很好的体验
                role.children = res.data.data;
              } else {
                this.$message.error("删除失败");
              }
            });
        })
        .catch(() => {
          this.$message.info("已取消删除");
        });
    },
    //分配角色权限
    setRolesButton(role) {
      this.roleId = role.id;
      this.$http({
        url: "rights/tree",
      }).then((res) => {
        console.log(res);
        // console.log(setRolesList);
        if (res.data.meta.status == 200) {
          this.setRolesList = res.data.data;
          console.log("role", role);
          this.getLeafKeys(role, this.defaultKeys);
          this.setRolesDialogVisible = true;
        }
      });
    },
    // 设置角色权限
    getLeafKeys(node, arr) {
      if (!node.children) {
        return arr.push(node.id);
      }
      node.children.forEach((item) => {
        this.getLeafKeys(item, arr);
      });
    },
    //监听分配权限对话框的关闭事件
    setRightsDialogClose() {
      this.defaultKeys = [];
    },
    //添加用户权限
    addRolesRights() {
      const keys = [
        ...this.$refs.treeRef.getCheckedKeys(),
        ...this.$refs.treeRef.getHalfCheckedKeys(),
      ];
      const idRids = keys.join(",");
      this.$http
        .post(`roles/${this.roleId}/rights`, { rids: idRids })
        .then((res) => {
          console.log(res);
          if (res.data.meta.status == 200) {
            this.$message.success("分配权限成功");
            this.getRolesList();
            this.setRolesDialogVisible = false;
          } else {
            this.$message.error("分配权限失败");
          }
        });
    },
  },
};
</script>

<style lang='less' scoped>
.el-tag {
  margin: 7px;
}
.bortop {
  border-top: 1px solid #ccc;
}
.borbot {
  border-bottom: 1px solid #ccc;
}
.cvcenter {
  display: flex;
  align-items: center;
}
</style>